package P8;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 使用Java中的UDP套接字实现文件上传的客户端和服务端程序
 * 8.1服务端程序
 */
public class UDPFileServer {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket
            DatagramSocket serverSocket = new DatagramSocket(12345);

            // 要保存文件的路径
            String filePath = "path/to/save/file.txt";
            File file = new File(filePath);

            // 创建输出流
            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
                byte[] buffer = new byte[1024];
                boolean fileComplete = false;

                while (!fileComplete) {
                    // 接收数据包
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    serverSocket.receive(packet);

                    // 将数据包内容写入文件
                    bos.write(packet.getData(), 0, packet.getLength());

                    // 检查是否接收完整文件
                    if (packet.getLength() < 1024) {
                        fileComplete = true;
                    }
                }
            }

            System.out.println("File saved successfully!");
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}